#!/usr/bin/env Rscript

library(tidyverse)
library(lubridate)

# Generate a summary considering current scope
summarize_scope <- function(x) {
    summarize (x,
               cnae_secao = names(which.max(table(cnae_secao))),
               ds_natureza_lesao = names(which.max(table(ds_natureza_lesao))),
               cbo_grande_grupo = names(which.max(table(cbo_grande_grupo))),
               agrupamento_parte_do_corpo = names(which.max(table(agrupamento_parte_do_corpo))),
               ds_grupo_agcausadores = names(which.max(table(ds_grupo_agcausadores))),
               ds_tipo_acidente = names(which.max(table(ds_tipo_acidente))),
               ds_tipo_local_acidente = names(which.max(table(ds_tipo_local_acidente))),
               ds_emitente_cat = names(which.max(table(ds_emitente_cat))),
               idade = round(mean(idade_cat), 2),
               obito = round(sum(cd_indica_obito == "S")/(n()), 2),
               sexo = round(sum(cd_tipo_sexo_empregado_cat == "Masculino")/(n()), 2),
               turno = round(sum(turno == "Diurno")/(n()), 2)
               )
}

brasil <- read_csv2("../app/data/brasil.csv")
complete <- read_csv2("../app/data/paracoord_data.csv")

# Summarize for every scope:
country <- group_by(complete, pais) %>% summarize_scope()
by_region <- group_by(complete, pais, regiao) %>% summarize_scope()
by_uf <- group_by(complete, regiao, uf) %>% summarize_scope()
by_meso <- group_by(complete, uf, mesorregiao) %>% summarize_scope()
by_micro <- group_by(complete, mesorregiao, microrregiao) %>% summarize_scope()
by_town <- group_by(complete, microrregiao, municipio) %>% summarize_scope()

# We need full information for towns
by_town <- brasil %>% inner_join(by_town, by = c("microrregiao", "municipio"))

# Write summaries
write_delim(country, "../app/data/treemap/sumario-pais.csv", delim = ";")
write_delim(by_region, "../app/data/treemap/sumario-regiao.csv", delim = ";")
write_delim(by_uf, "../app/data/treemap/sumario-uf.csv", delim = ";")
write_delim(by_meso, "../app/data/treemap/sumario-meso.csv", delim = ";")
write_delim(by_micro, "../app/data/treemap/sumario-micro.csv", delim = ";")
write_delim(by_town, "../app/data/treemap/sumario-municipio.csv", delim = ";")
